import 'dart:io';
import 'package:demo/config/app_resource.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:demo/views/msg/msg_forward_controller.dart';
import 'package:demo/views/msg/msg_forward_view.dart';
import 'package:demo/tools/tools_enum.dart';
import 'package:demo/tools/tools_perms.dart';
import 'package:demo/tools/tools_scan.dart';
import 'package:demo/component/component_bottom.dart';
import 'package:demo/component/component_common.dart';
import 'package:demo/component/component_image.dart';
import 'package:photo_view/photo_view_gallery.dart';

double maxHeight = 400;
double minHeight = 50;
double maxWidth = 180;

// 聊天=消息=图片
class ChatMessageImage extends StatelessWidget {
  final Map<String, dynamic> content;

  const ChatMessageImage(
    this.content, {
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {
        Get.to(
          ChatMessageImageShow(content),
          transition: Transition.topLevel,
        );
      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(10),
        child: Container(
          constraints: BoxConstraints(
            maxHeight: maxHeight,
            minHeight: minHeight,
          ),
          width: maxWidth,
          child: ComponentImage(
            content['data'],
            ImageType.file,
            fit: BoxFit.contain,
            width: double.infinity,
            height: _calculate(content),
          ),
        ),
      ),
    );
  }

  // 计算
  _calculate(Map<String, dynamic> content) {
    int width = content['width'] ?? 200;
    int height = content['height'] ?? 200;
    double value = height / width * maxWidth;
    if (value > maxHeight) {
      return maxHeight;
    }
    if (value < minHeight) {
      return minHeight;
    }
    return value;
  }
}

// 图片组件
class ChatMessageImageShow extends StatefulWidget {
  final Map<String, dynamic> content;
  const ChatMessageImageShow(this.content, {super.key});

  @override
  createState() => _ShowImageState();
}

class _ShowImageState extends State<ChatMessageImageShow> {
  @override
  void dispose() {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Map<String, dynamic> content = widget.content;
    return Scaffold(
      body: InkWell(
        onTap: () {
          Get.back();
        },
        onLongPress: () {
          ComponentBottom([
            BottomModel(
              '保存',
              onTap: () async {
                // 关闭
                Get.back();
                // 权限
                bool result = await ToolsPerms.storage();
                if (!result) {
                  return;
                }
                // 保存
                await ComponentCommon.saveFile(content['data'], '.png');
              },
            ),
            BottomModel(
              '转发',
              onTap: () async {
                // 关闭
                Get.back();
                // 转发
                await Get.toNamed(
                  MsgForwardView.routeName,
                  arguments: [
                    ForwardModel(MsgType.image, content),
                  ],
                );
              },
            ),
            if (content['scan'] != null)
              BottomModel(
                '识别二维码',
                onTap: () async {
                  // 关闭
                  Get.back();
                  // 执行扫码
                  ToolsScan.doScan(content['scan']);
                },
              ),
          ]);
        },
        child: PhotoViewGallery.builder(
          itemCount: 1,
          builder: (context, index) {
            String data = content['data'];
            ImageProvider provider = FileImage(File(data));
            return PhotoViewGalleryPageOptions(
              imageProvider: provider,
              errorBuilder: (context, error, stackTrace) {
                return Image.asset(AppImage.error);
              },
            );
          },
          scrollPhysics: const BouncingScrollPhysics(),
          backgroundDecoration: const BoxDecoration(
            color: Colors.white,
          ),
        ),
      ),
    );
  }
}
